<template>
  <el-form :model="formParam" :rules="rulesInformation" ref="custForm"> 
    <el-table :data="recordData" width="1300px" :span-method="arraySpanMethod" stripe :border="true">
      <el-table-column prop="name" label=""  width="150" />
      <el-table-column prop="" label="INVOICE"  :width="formWidth">
        <template #default="scope">
          <el-form-item v-if="scope.$index == 0" size="small" prop="epdaInvoiceFile"> 
            <DragUpload
            :limit="2"
            accept=".pdf,.docx,.xlsx,.doc,.docx,.txt,.zip,.rar,.jpg,.png,.jpeg"
            @upload-start="handleUploadStart($event,'epdaInvoiceFile')"
            @files-change="handleFilesChange($event,'epdaInvoiceFile')"
            @file-removed="handleFileRemoved($event,2)"
            v-model="epdaInvoice"
            />
          </el-form-item>
          <el-form-item v-if="scope.$index == 1" prop="fdaInvoiceFile" size="small" > 
            <DragUpload
            :limit="2"
            accept=".pdf,.docx,.xlsx,.doc,.docx,.txt,.zip,.rar,.jpg,.png,.jpeg"
            :maxSize="20"            
            @upload-start="handleUploadStart($event,'fdaInvoiceFile')"
            @files-change="handleFilesChange($event,'fdaInvoiceFile')"
            @file-removed="handleFileRemoved($event,3)"
            v-model="fdaInvoice"
            />
          </el-form-item>        
          <el-form-item v-if="scope.$index == 4" prop="balanceCloseDate" style="width: 60%;">
            <el-date-picker type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
              v-model="formParam.balanceCloseDate" placeholder="Please select" style="width: 100%;" />
          </el-form-item>
          <el-form-item v-if="scope.$index == 5" prop="remark" style="width: 100%;">
            <el-input type="textarea" v-model="formParam.remark" clearable :rows="2" maxlength="255" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="AMOUNT" header-align="center" width="200">
        <template #default="scope">
          <el-form-item v-if="scope.$index == 0" prop="epdaAmount">
            <el-input-number v-model="formParam.epdaAmount" :precision="2" :step="0.1" :max="100000000"
              :controls="false" style="width: calc(100% - 70px)" clearable />
            <el-select v-model="formParam.currency" style="width: 70px">
              <el-option v-for="item in currency_type" :value="item.label" :label="item.label" :key="item.label" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="scope.$index == 1" prop="fdaAmount"> 
            <el-input-number v-model="formParam.fdaAmount" :precision="2" :step="0.1" :max="100000000" :controls="false"
              style="width: calc(100% - 60px)" />
            <span class="currency-content">{{ formParam.currency }}</span>
          </el-form-item>
          <el-form-item v-if="scope.$index == 2" prop="etd">
            <el-input-number :model-value="computedValue" :controls="false" :disabled="true" class="number-content" />
            <span class="currency-content">{{ formParam.currency }}</span> 
          </el-form-item> 
          <el-form-item v-if="scope.$index == 3" prop="etd">
            <el-input-number  v-model="formParam.combineBalance" :controls="false" :disabled="true" class="number-content" />
            <span class="currency-content">{{ formParam.currency }}</span> 
          </el-form-item>  
        </template>
      </el-table-column>
      <el-table-column label="DATE ISSUE" header-align="center" width="140">
        <template #default="scope">
          <el-form-item v-if="scope.$index == 0">
            <el-date-picker type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="formParam.epdaIssueDate" />
          </el-form-item>
          <el-form-item v-if="scope.$index == 1">
            <el-date-picker type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="formParam.fdaIssueDate"
              />
          </el-form-item>
          <el-form-item v-if="scope.$index == 2" style="text-align: center;justify-content: center;" prop="balanceType">
            <el-radio-group v-model="formParam.balanceType">
              <el-radio value="0" label="0">TO RECOVER</el-radio>
              <el-radio value="1" label="1">TO MAKE UP</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="DATE PAID" header-align="center" width="150">
        <template #default="scope">
          <el-form-item v-if="scope.$index == 0">
            <el-date-picker type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="formParam.paidDate" />
          </el-form-item>
          <el-form-item v-if="scope.$index == 2" prop="balanceSlipFile" >
            <!-- <el-button type="primary" plain icon="upload" size="small" onclick="this.nextSibling.click()"/> 
            <input type="file" id="upload-file-balanceSlipFile" v-show="false"
              @change="uploadFile($event, 'balanceSlipFile')" accept=".pdf,.xlsx,.png,.jpg,jpeg,.docx,.zip,.rar,.txt" />
              <a href="javascript:void(0)" :class="formParam.balanceSlipFile||formParam.balanceSlip?'upload-wrapper':''" @click="downloadPDF(formParam.balanceSlip)"><span v-if="formParam.balanceSlip||formParam.balanceSlipFile"  @click.stop="removeFile('balanceSlipFile')">×</span>{{
              formParam.balanceSlipFile?.name || getFileName(formParam.balanceSlip)
            }}</a> -->
            <DragUpload
            :limit="2"
            accept=".pdf,.docx,.xlsx,.doc,.docx,.txt,.zip,.rar,.jpg,.png,.jpeg"
            :maxSize="5"
            @upload-start="handleUploadStart($event,'balanceSlipFile')"
            @files-change="handleFilesChange($event,'balanceSlipFile')"
            @file-removed="handleFileRemoved($event,5)"
            v-model="balanceSlip"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="BANK SLIP"  :width="formWidth">
        <template #default="scope">
          <el-form-item v-if="scope.$index == 0" prop="epdaAmount" class="dropbox-epdaBankSlipFile">
            <!-- <el-button type="primary" plain icon="upload" size="small"  onclick="this.nextSibling.click()"/> 
            <input type="file" id="upload-file-epdaBankSlipFile" v-show="false"
              @change="uploadFile($event, 'epdaBankSlipFile')" accept=".pdf,.xlsx,.png,.jpg,jpeg,.docx,.zip,.rar,.txt" />
            <a href="javascript:void(0)"  :class="formParam.epdaBankSlipFile||formParam.epdaBankSlip?'upload-wrapper':''" @click="downloadPDF(formParam.epdaBankSlip)"><span v-if="formParam.epdaBankSlipFile||formParam.epdaBankSlip"  @click.stop="removeFile('epdaBankSlipFile')">×</span>{{
              formParam.epdaBankSlipFile?.name || getFileName(formParam.epdaBankSlip)
            }}</a> -->
            <DragUpload
            :limit="2"
            accept=".pdf,.docx,.xlsx,.doc,.docx,.txt,.zip,.rar,.jpg,.png,.jpeg"
            :maxSize="5"
            @upload-start="handleUploadStart($event,'epdaBankSlipFile')"
            @files-change="handleFilesChange($event,'epdaBankSlipFile')"
            @file-removed="handleFileRemoved($event,4)"
            v-model="epdaBankSlip"
            />
          </el-form-item>
        </template>
      </el-table-column> 
    </el-table>
  </el-form>
  <div class="pane-footer" v-hasPermi="['schedule:epdaFda:edit']">
    <el-button type="warning"  v-if="combineVisible" @click="combineHandle">Combine Settlement</el-button>
     <el-button type="warning" v-if="formParam.combineBalance" @click="undoCombineHandle">UNDO</el-button>
    <el-button @click="cancelHandle"   >{{ $t("ship.button.cancel") }}</el-button>
    <el-button type="primary"    @click="submitForm">{{ $t("ship.button.submit") }}</el-button>
  </div>
</template>
<script lang="ts" setup>
// @ts-nocheck
import { ref, onMounted,onUnmounted, computed, reactive, nextTick, defineEmits, watch } from "vue";
import service from "@/utils/request";
import { convertUrl } from "@/utils/tencentCos";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import DragUpload from '@/components/FormDataIUpload/index.vue'; 
import { id } from "element-plus/es/locales.mjs";

const proxy = getCurrentInstance()?.proxy;
const props = defineProps({
  data: {
    type: Object,
    default: () => { }
  },
  rowData: {
    type: Object,
    default: () => { }
  },
  portRotationId: {
    type: Number,
    default: 0
  },
  titleValue: {
    type: String,
    default: ""
  }
});
const emit = defineEmits(["saveOk",'getDetail']);
const custForm = ref(null);
const currency_type = ref([]);

const initForm = reactive({

});
const formParam = ref({
  id: null,
  portRotationId: props.portRotationId,
  epdaAmount: "0.0",
  fdaAmount: "0.0", 
  balanceCloseDate: null,
  epdaIssueDate: null,
  fdaIssueDate: null,
  paidDate: null,
  currency: "USD",
  remark: ""
});

let recordData = ref([
  {
    name: "EPDA",
    ETA: null,
    ATA: null,
    ETD: null,
    ATD: "",
    ACTIVITY: "",
    VOYAGESOF: "" 
  },
  {
    name: "FDA",
    ETA: null,
    ATA: null,
    ETD: null,
    ATD: "",
    ACTIVITY: "",
    VOYAGESOF: ""
  },
  {
    name: "BALANCE",
    ETA: null,
    ATA: null,
    ETD: null,
    ATD: "",
    ACTIVITY: "",
    VOYAGESOF: "",
    REMARK: ""
  },
  {
    name: "COMBINED BALANCE",
     ETA: null,
     ATA: null,
     ETD: null,
     ATD: "",
     ACTIVITY: "",
     VOYAGESOF: "",
     REMARK: ""
  },
  {
    name: "CLOSE DATE",
    ETA: null,
    ATA: null,
    ETD: null,
    ATD: "",
    ACTIVITY: "",
    VOYAGESOF: "",
    REMARK:""
  } ,
  {
    name: "REMARKS",
    ETA: null,
    ATA: null,
    ETD: null,
    ATD: "",
    ACTIVITY: "",
    VOYAGESOF: "",
    REMARK: ""
  }  
]);

let combineVisible = ref(false)
let combineId = null;

onMounted(async () => {
  let item =  props.rowData.details.find( i =>i.id == props.portRotationId) 
  for(let i in props.rowData.details){
     if(props.rowData.details[i].id != item.id && props.rowData.details[i].portName == item.portName){ 
        combineVisible.value = true;
        combineId = props.rowData.details[i].id
        break;
     }
  } 
 
  const res = await proxy.useDict("currency_type");
  currency_type.value = res.currency_type.value;
  window.addEventListener('resize', updateDialogWidth);
  updateDialogWidth()
});
const formWidth=ref('230')
const updateDialogWidth = () => {
  const width = window.innerWidth;
  formWidth.value = width >= 1200 ? '' : width >= 768 ? '230' : '200';
};
const balanceSlip = ref([])
const epdaBankSlip = ref([])
const fdaInvoice = ref([])
const epdaInvoice = ref([])
watch(
  () => props.data,
  val => {
    //判断一下val是不是非空对象  
    if (Object.keys(val).length !== 0) {
      formParam.value = Object.assign(val, { currency: val.currency || 'USD' });
      if(formParam.value.balanceBankSlip){
         balanceSlip.value =[]
        let balanceBankSlips =  formParam.value.balanceBankSlip.split("&&&");
        for(let i in balanceBankSlips){
          balanceSlip.value.push({name:getFileName(balanceBankSlips[i]),url: balanceBankSlips[i]})
        }
        //balanceSlip.value=[{name:getFileName(formParam.value.balanceBankSlip),url:formParam.value.balanceBankSlip}]
      }else{
        balanceSlip.value=[]
      }
      if(formParam.value.epdaBankSlip){
        epdaBankSlip.value =[]
        let epdaBankSlips =  formParam.value.epdaBankSlip.split("&&&");
        for(let i in epdaBankSlips){
          epdaBankSlip.value.push({name:getFileName(epdaBankSlips[i]),url: epdaBankSlips[i]})
        }
        //epdaBankSlip.value=[{name:getFileName(formParam.value.epdaBankSlip),url:formParam.value.epdaBankSlip}]
      }else{
        epdaBankSlip.value=[]
      }
      if(formParam.value.fdaInvoice){
        fdaInvoice.value= []
        let fdaInvoices =  formParam.value.fdaInvoice.split("&&&");
         for(let i in fdaInvoices){
          fdaInvoice.value.push({name:getFileName(fdaInvoices[i]),url: fdaInvoices[i]})
        }
       // fdaInvoice.value=[{name:getFileName(formParam.value.fdaInvoice),url:formParam.value.fdaInvoice}]
      }else{
        fdaInvoice.value=[]
      }
      if(formParam.value.epdaInvoice){
        epdaInvoice.value=[]
        let epdaInvoices =  formParam.value.epdaInvoice.split("&&&");
        for(let i in epdaInvoices){
          epdaInvoice.value.push({name:getFileName(epdaInvoices[i]),url: epdaInvoices[i]})
        }
        //epdaInvoice.value=[{name:getFileName(formParam.value.epdaInvoice),url:formParam.value.epdaInvoice}]
      }else{
        epdaInvoice.value=[]
      }
      return;
    }
  },
  { deep: true, immediate: true }
);
const initUploadFile=(key)=>{
  if(formParam.value[key]){
    key.value=[{name:getFileName(formParam.value[key]),url:formParam.value[key]}]
  }else{
    key.value=[]
  }
}
const handleUploadStart=(files,type)=> {
   console.log('开始上传:', files);
}
const handleFilesChange=(files,type)=> {
  formParam.value[type]=files.map((item)=>{
    return item.file
  })
}

const handleFileRemoved=(file,type)=> {
  if(file.url) {
    deleteFile(file,type)
  }
}
const deleteFile = (file,type) => {
  let params = {id:formParam.value.id,type:type,url: file.url }
  service.post(`shipping/schedule/deleteFile`,params).then(res=>{
    ElNotification.success({
        title: "Prompt information",
        message: "Delete successful!",
        position: "bottom-right",
    });
    emit('getDetail',formParam.value.portRotationId)
  })
}
const computedValue = computed(() => {
  if (formParam.value.fdaAmount == null) {
    formParam.value.balanceType = null
    return null
  }
  let result = Number(((formParam.value.fdaAmount || 0) - (formParam.value.epdaAmount || 0)).toFixed(2));
  formParam.value.balanceType = result >= 0 ? '1' : '0'

  return result
});


const activitys = ["LOADING", "DISCHARGING", "BUNKERING", "D/D or SURVEY", "CREW CHANGE","PASSING"];

// 表格验证
const rulesInformation = ref({});

const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => {
  // @ts-ignore 
  custForm.value.validate(async valid => {
    if (!valid) {
      // @ts-ignore
      ElNotification.warning({
        title: "Prompt information",
        message: "verification not success！",
        position: "bottom-right"
      });
      return;
    }
    const typeList=['balanceSlipFile','epdaBankSlipFile','fdaInvoiceFile','epdaInvoiceFile']
    const formData = new FormData()
    for (const [k, n] of Object.entries(formParam.value)) {
      if (typeList.includes(k) && Array.isArray(n)) { 
        for (let i = 0; i < n.length; i++) {
          formData.append(k, n[i]); 
        }
      }else if(n){
        formData.append(k, n);
      }
    }

    await service.post("shipping/schedule/updateEpdaFda", formData);
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right"
    });
    emit("saveOk");
  });
};
const cancelHandle = () => {
  emit("saveOk");
};

const combineHandle = ()=>{
   ElMessageBox.confirm("Are you sure to combine the selected settlements? The total balance will be recalculated?", "Confirmation Information", {
        type: "warning",
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
      }).then(async () => {
        let params = {id: props.portRotationId,combineId:combineId }
         await service.put("shipping/schedule/combineBalance", params);

          // @ts-ignore
          ElNotification.success({
            title: "Prompt information",
            message: "save successful!",
            position: "bottom-right"
          });
          emit("saveOk");
      }); 
}

const undoCombineHandle = ()=>{
    ElMessageBox.confirm("Are you sure to undo the combine balance?", "Confirmation Information", {
        type: "warning",
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
      }).then(async () => {
        let params = {id: props.portRotationId,combineId:combineId }
         await service.put("shipping/schedule/undoCombineBalance", params);

          // @ts-ignore
          ElNotification.success({
            title: "Prompt information",
            message: "save successful!",
            position: "bottom-right"
          });
          emit("saveOk");
      }); 
}

// 获取文件名称
function getFileName(name) {
  if (name == null) {
    return name;
  }
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 1) {
    if (rowIndex === 5) {
      return [2, 5];
    }
     
  }
  if (columnIndex === 3) {
    if (rowIndex === 2) {
      return [1, 2];
    }
  }
};


</script>
<style lang="scss" scoped>
.el-table__expand-column .cell {
  display: none;
}

.c-expand {
  color: #888;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  cursor: pointer;
  width: 100%;
  height: 100%;
}

.c-expand i {
  font-size: 16px;
}

.c-expand i.expand {
  font-size: 16px;
  transform: rotate(90deg);
  transition: all 0.25s;
}

::v-deep(.el-table__header) {
  line-height: 48px !important;
  height: 48px;
}

::v-deep(.el-table) {
  .el-table_6_column_33 {
    .cell {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

::v-deep(.el-date-editor) {
  width: 160px;
}

.header-wrapper {
  border: 1px solid #ebeef5;
  border-bottom: none;
  padding: 10px;
}

.daf-table {
  margin: 0;
  padding: 0;
}

.tips {
  text-align: right;

  .el-button {
    margin-left: 10px;
    margin-right: 15px;
  }
}

.pane-footer {
  margin-top: 20px;
  text-align: right;
}

.custom-select-dropdown .el-select-dropdown__item .el-icon-circle-close {
  display: none;
}

::v-deep(.handle_activity) {
  .select-trigger {
    .el-select__tags {
      .el-select-tags-wrapper {
        .el-tag {
          i {
            display: none;
          }
        }
      }
    }
  }
}

.number-content {
  width: calc(100% - 60px);
}

.currency-content {
  display: inline-block;
  width: 60px;
  text-align: center;
}
.upload-wrapper{
  display: flex;
   border: 1px solid #d9d9d9;
   border-radius: 2px;
   line-height: 22px;
   padding: 0 5px;
   >span{
    color: #04a9eb;
    font-size: 24px;
    vertical-align: middle;
    margin-right: 2px;
   display: none;
   }
}
.upload-wrapper:hover{
   >span{
    display: block;
   }
   cursor: pointer;
}
</style>